package com.cheng.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cheng.entity.MsgRespose;
import com.cheng.entity.Tieba;
import com.cheng.service.TiebaService;
import com.cheng.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cheng.utils.TiebaUtil.checkFields;
import static com.cheng.utils.TiebaUtil.selectRows;

/**
 * @author Cheng
 * @since 2019-07-18
 */
@RestController
@RequestMapping("/tieba")
public class TiebaController {
    @Autowired
    private TiebaService tiebaService;
    @Autowired
    private TiebaUtil tiebaUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    private int execute = 0;

    private static final Logger logger = LoggerFactory.getLogger(TiebaController.class);

    @Scheduled(cron = "0 0/1 * * * ?")
    public void tiebaTask() throws Exception {
        List<Tieba> list = tiebaService.selectList(Condition.create().eq("validity", 1)
                .andNew().lt("finish_time", DateUtil.getDateStr())
                .or().isNull("finish_time")
                .last("limit 2"));
//        limit 2只是我每次定时器只执行两个记录而已可以随意修改 也可以随意修改定时器间隔
        for (Tieba tieba : list) {
            logger.info("Sign:{}", tieba);
            tiebaUtil.sign(tieba);
        }
        logger.info("execute:{}, 执行时间{}", ++execute, DateUtil.getDate());
    }

    /**
     * 添加任务
     *
     * @param tieba
     * @return
     */
    @PostMapping("/add")
    public MsgRespose addTb(@RequestBody Tieba tieba, HttpServletRequest request) {
        logger.info("添加：{}", tieba);
        MsgRespose msgRespose = new MsgRespose();
        if (checkFields(tieba) == false) {
            return msgRespose.setCode(1004).setMsg("参数不能为空!");
        }
        if (tieba.getBduss().length() != 192) {
            return msgRespose.setCode(1007).setMsg("BDUSS为192位字符，请核实bduss是否正确!");
        }
        if (!tieba.getQq().matches("[0-9]{5,}")) {
            return msgRespose.setCode(1006).setMsg("QQ为至少5位纯数字,不能有空格!");
        }
        try {
            if (TiebaSign.verification(tieba.getBduss()) == null) {
                return msgRespose.setCode(1001).setMsg("bduss验证不通过!");
            }
            List list = tiebaService.selectList(Condition.create().eq("bduss", tieba.getBduss()));
            if (list.size() >= 1) {
                return msgRespose.setCode(1003).setMsg("bduss已存在!");
            }
            CookieUtil.setCookie(request, response, "qq", tieba.getQq(), 3600 * 24 * 30, "UTF-8");
            tieba.setCreatTime(DateUtil.getDate()).setValidity(1);
            tieba.setIp(CusAccessObjectUtil.getIpAddress(request));
            tiebaService.insert(tieba);
        } catch (Exception e) {
            e.printStackTrace();
            return msgRespose.setCode(1002).setMsg("添加贴吧签到任务失败!");
        }
        return msgRespose.setCode(1000).setMsg("添加贴吧签到任务成功!");
    }

    /**
     * 搜索
     *
     * @param qq
     * @return
     */
    @GetMapping("/search")
    public MsgRespose search(String qq) {
        MsgRespose msgRespose = new MsgRespose();
        if (StringUtils.isBlank(qq)) {
            CookieUtil.setCookie(request, response, "qq", "", 3600 * 24 * 30, "UTF-8");
            return msgRespose.setCode(1004).setMsg("参数不能为空!");
        }
        List<Tieba> list = tiebaService.selectList(new EntityWrapper<Tieba>().eq("qq", qq));
        for (Tieba tieba : list) {
            tieba.setBduss(null);
            tieba.setForumList(null);
            tieba.setDel(null);
            tieba.setIp(null);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("rows", list);
        msgRespose.setCode(1000).setMsg(map);
        logger.info("Search qq：{}", qq);
        if (StringUtils.isNotBlank(qq) && !"null".equals(qq)) {
            CookieUtil.setCookie(request, response, "qq", qq, 3600 * 24 * 30, "UTF-8");
        }
        return msgRespose;
    }

    /**
     * 修改用户
     *
     * @param tieba
     * @return
     */
    @PostMapping("/update")
    public MsgRespose update(@RequestBody(required = false) Tieba tieba) {
        MsgRespose msgRespose = new MsgRespose();
        tieba.setQq(null);
        try {
            if (StringUtils.isNotBlank(tieba.getBduss()) && TiebaSign.verification(tieba.getBduss()) == null) {
                return msgRespose.setCode(1001).setMsg("bduss验证不通过!");
            }
            tieba.setValidity(1);
            boolean b = tiebaService.updateById(tieba);
            if (b == false) {
                return msgRespose.setCode(1005).setMsg("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return msgRespose.setCode(1005).setMsg("更新失败");
        }
        return msgRespose.setCode(1000).setMsg("修改成功");
    }

    /**
     * 获得更新时弹出输入框内容
     *
     * @param id
     * @return
     */
    @GetMapping("/getUpdate")
    public MsgRespose getUpdateOne(String id) {
        MsgRespose msgRespose = new MsgRespose();
        Tieba tieba = tiebaService.selectById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("id", tieba.getId());
        map.put("qq", tieba.getQq());
        map.put("taskname", tieba.getTaskname());
        return msgRespose.setCode(1000).setMsg(map);
    }

    /**
     * 查询签到错误
     *
     * @param id
     * @return
     */
    @GetMapping("/findOne")
    public MsgRespose findOne(String id) {
        MsgRespose msgRespose = new MsgRespose();
        Tieba tieba = tiebaService.selectById(id);
        String forumList = tieba.getForumList();
        JSONObject jsonObject = (JSONObject) JSONObject.parse(forumList);
        JSONObject jo = null;
        try {
            JSONArray rows = jsonObject.getJSONArray("rows");
            jo = new JSONObject();
            jo.put("finishTime", tieba.getFinishTime());
            jo.put("patherror", selectRows(rows, "2"));
            jo.put("blacklist", selectRows(rows, "3"));
            jo.put("loadfail", selectRows(rows, "4"));
            jo.put("ban", selectRows(rows, "5"));
        } catch (Exception e) {
            e.printStackTrace();
            return msgRespose.setCode(1002).setMsg("fail!");
        }
        return msgRespose.setCode(1000).setMsg(jo);
    }
}
